<?php

namespace app\admin\controller;

use app\admin\model\ShopCategoryModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Request;

class ShopCategoryController extends AdminBaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $param = $this->request->param();
        $list = ShopCategoryModel
                ::where(function($query) use($param){
                    if(isset($param['shop_name']) && !empty($param['shop_name'])){
                        $title = $param['shop_name'];
                        $query->where('shop_name','like','%'.$title.'%');
                    }
                })
            ->field('*')
            ->order('id desc')
            ->paginate(null,false,['query'=>$param]);
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $model = new ShopCategoryModel();
        $res = $model->allowField(true)->create($request->param());
        if($res){
            $this->success('添加成功!', url('ShopCategory/index'));
        }else{
            $this->error('失败');
        }
    }


    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        if ( ! $data = ShopCategoryModel::get($id)){
            $this->error('数据不存在');
        }

        $this->assign('data',$data);
        return $this->fetch();
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, ShopCategoryModel $model)
    {
        $data = $request->param();

        // 过滤data数组中的非数据表字段数据
        $res = $model->allowField(true)->update($data,['id'=>$data['id']]);
        if($res){
            $this->success('保存成功!', url('ShopCategory/index'));
        }else{
            $this->error('失败');
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id,ShopCategoryModel $model)
    {
        if ( ! $data = $model->get($id)){
            $this->error('数据不存在');
        }
       
        $model::destroy(['id'=>$id]);
        $this->success('删除成功!');
    }
}
